﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;

namespace Wwtfly.DBUtility
{
    /// <summary>
    ///  帮助类
    /// </summary>
    public class DBHelper
    {

        /// <summary>
        /// 执行存储过程，返回 SqlDataReader，使用后手动释放资源
        /// </summary>
        /// <param name="sqlString">sql语句</param>
        /// <param name="sqlParams">sql 参数</param>
        /// <returns>SqlDataReader</returns>
        public static IDataReader ExecuteReader(string sqlString, params DbParameter[] dbParams)
        {
            return ExecuteReader(null, sqlString, dbParams);
        }

        /// <summary>
        /// 执行存储过程，返回 SqlDataReader，使用后手动释放资源
        /// </summary>
        /// <param name="name">数据库的链接名称</param>
        /// <param name="sqlString">存储过程名称</param>
        /// <param name="sqlParams">sql 参数</param>
        public static IDataReader ExecuteReader(string name, string sqlString, params DbParameter[] dbParams)
        {
            Database db = name == null ? DatabaseFactory.CreateDatabase() : DatabaseFactory.CreateDatabase(name);
            DbCommand dbCommand = db.GetSqlStringCommand(sqlString);
            PrepareCommand(dbCommand, dbParams);
            return db.ExecuteReader(dbCommand);
        }

        /// <summary>
        /// 组合参数
        /// </summary>
        /// <param name="cmd">command 对象</param>
        /// <param name="dbParams">参数组</param>
        protected static void PrepareCommand(DbCommand cmd, params DbParameter[] dbParams)
        {
            if (!object.Equals(dbParams, null))
            {
                foreach (DbParameter parm in dbParams)
                {
                    if (!object.Equals(parm, null))
                    {
                        if ((parm.Direction == ParameterDirection.Input ||
                            parm.Direction == ParameterDirection.InputOutput) &&
                            object.Equals(parm.Value, null))
                        {
                            parm.Value = DBNull.Value;
                        }
                        //if ((parm.DbType == DbType.AnsiString || parm.DbType == DbType.String)
                        //    && (parm.Value == null || parm.Value == DBNull.Value))
                        //{
                        //    parm.Value = string.Empty;
                        //}
                        cmd.Parameters.Add(parm);
                    }
                }
            }
        }



    }
}
